package com.afdor.rws.event.driven.channel.aliyun.mns.consumer.retry;

import com.afdor.rws.annotation.extension.Extension;
import com.afdor.rws.event.driven.api.channel.consumer.EventConsumer;
import com.afdor.rws.event.driven.api.channel.consumer.handler.EventRetryStrategy;
import com.afdor.rws.event.driven.channel.aliyun.mns.utils.AliyunMnsEventHolder;
import com.afdor.rws.event.driven.entities.Event;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.ToString;

/**
 * 阿里云事件重试策略
 *
 * @author 悭梵
 * @date Created in 2018-08-21 10:29
 */
@ToString
@EqualsAndHashCode
@NoArgsConstructor
@Extension(value = "aliyunMns", order = Extension.NORMAL_ORDER - 100, scope = Extension.Scope.PROTOTYPE, interfaceClass = EventRetryStrategy.class)
public class AliyunEventRetryStrategy implements EventRetryStrategy<AliyunMnsEventHolder> {

    @Getter
    private EventConsumer eventConsumer;

    @Getter
    private int maxRetryCount = 3;

    public AliyunEventRetryStrategy(EventConsumer eventConsumer) {
        this();
        this.eventConsumer = eventConsumer;
    }

    @Override
    public boolean allowRetry(AliyunMnsEventHolder eventHolder) {
        return eventHolder.getEvent() != null && eventHolder.getDequeueCount() < getMaxRetryCount();
    }

    @Override
    public void retry(AliyunMnsEventHolder eventHolder) {
        // 由mns实现消息重试，这里只记录次数
        Event event = eventHolder.getEvent();
        if (event != null) {
            event.setRetryCount(eventHolder.getDequeueCount());
        }
    }
}
